package com.genexususa.eo.bing.data.requests;

import com.genexususa.eo.bing.data.GxItemException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GxKeywordsRequest {
    private long gxCampaignId;
    private long bingCampaignId;
    private GxKeywordsAdGroupRequest[] keywordsAdGroupRequests;

    public GxKeywordsRequest(Element element) throws IllegalArgumentException, GxItemException {
        if (element.getElementsByTagName("GxCampaignId").getLength() > 0 &&
            element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.gxCampaignId = Long.valueOf(((Node)element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing external Campaign id");
        }
        if (element.getElementsByTagName("BingCampaignId").getLength() > 0 &&
            element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.bingCampaignId = Long.valueOf(((Node) element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing Bing Campaign id");
        }
        NodeList keywordsAdGroupRequestsNode = element.getElementsByTagName("KeywordsAdGroupRequestCollection");
        if (keywordsAdGroupRequestsNode.getLength() > 0) {
            NodeList keywordsAdGroupRequestNode = ((Element)keywordsAdGroupRequestsNode.item(0)).getElementsByTagName("KeywordsAdGroupRequest");
            if (keywordsAdGroupRequestNode.getLength() <= 0) {
                throw new GxItemException("No AdGroups were found for Campaign " + this.gxCampaignId);
            }
            this.keywordsAdGroupRequests = new GxKeywordsAdGroupRequest[keywordsAdGroupRequestNode.getLength()];
            for (int i=0; i<keywordsAdGroupRequestNode.getLength(); i++) {
                keywordsAdGroupRequests[i] = new GxKeywordsAdGroupRequest((Element)keywordsAdGroupRequestNode.item(i));
            }
        } else {
            this.keywordsAdGroupRequests = new GxKeywordsAdGroupRequest[0];
        }
    }

    public long getGxCampaignId() {
        return gxCampaignId;
    }

    public long getBingCampaignId() {
        return bingCampaignId;
    }

    public GxKeywordsAdGroupRequest[] getKeywordsAdGroupRequests() {
        return keywordsAdGroupRequests;
    }
}
